package io.gitee.chearnee.fw.socket;

import io.gitee.chearnee.fw.socket.component.NettyChannelInitializer;
import io.gitee.chearnee.fw.socket.config.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

@Slf4j
public class NettyServerBootstrap {
    @Autowired
    private NettyProperties nettyProperties;
    @Autowired
    @Qualifier(value = "bossGroup")
    private NioEventLoopGroup bossGroup;
    @Autowired
    @Qualifier(value = "workGroup")
    private NioEventLoopGroup workGroup;
    private ChannelFuture f = null;

    public void run() throws Exception {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyChannelInitializer());
        serverBootstrap.option(ChannelOption.SO_BACKLOG, nettyProperties.getBacklog());
//                .option(ChannelOption.SO_KEEPALIVE, nettyProperties.isKeepAlive())
//                //通过NoDelay禁用Nagle,使消息立即发出去，不用等待到一定的数据量才发出去
//                .option(ChannelOption.TCP_NODELAY,true);
        serverBootstrap.localAddress(nettyProperties.getPort());
        f = serverBootstrap.bind().sync();
        if(f.isSuccess()){
            log.info("netty启动成功");
        }
    }

    public void destroy() {
        try {
            if (f != null) {
                f.channel().closeFuture().sync();// 关闭服务器通道
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully().syncUninterruptibly();
            workGroup.shutdownGracefully().syncUninterruptibly();
        }
    }
}
